package com.wenyu.wenyuyuedu.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.circle.SearchResultActivity;
import com.wenyu.wenyuyuedu.adapter.circleAdapter.SearchAdapter;
import com.wenyu.wenyuyuedu.bean.SearchActivityBean;
import com.wenyu.wenyuyuedu.bean.circle.SearchBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.SearchServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyLinearLayout;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/*
* 搜索的Activity
* */
public class SearchActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.circle_et_sousuo)
    EditText circleEtSousuo;
    @InjectView(R.id.search_quit)
    TextView searchQuit;
    @InjectView(R.id.tv_batch_search)
    TextView tvBatchSearch;
    @InjectView(R.id.tv_search_clear)
    TextView tvSearchClear;
    @InjectView(R.id.ll_hot_search)
    LinearLayout llHotSearch;
    @InjectView(R.id.my_linearlayout)
    MyLinearLayout myLinearlayout;
    @InjectView(R.id.lv_search)
    ListView lvSearch;
    private Intent intent;
    private String token;
    private List<SearchBean.InfoBean.HistoryBean> history;
    private List<SearchBean.InfoBean.HistoryBean> historyAll = new ArrayList<>();
    private SearchAdapter adapter;
    private List<SearchBean.InfoBean.HotBean> hot;
    private List<SearchBean.InfoBean.HotBean> cacheList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        StatusBarUtil.setStatusBar(SearchActivity.this, R.color.white);
        ButterKnife.inject(this);
        Search();
        initView();
        initPutoRefresh();
        request();
    }
    /*
          * 初始化刷新的控件
          * */
    private void initPutoRefresh() {
        lvSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String search_key = history.get(i).getSearch_key();
                intent.setClass(SearchActivity.this,SearchResultActivity.class);
                intent.putExtra("searchkey",search_key);
                startActivity(intent);
            //   search(search_key);
            }
        });
    }

    /*
    * 历史搜索   * */
    private void request() {
        SearchServer searchServer = ApiWrapper.getInstance().create(SearchServer.class);
        Call<SearchBean> search = searchServer.getSearch(token);
        search.enqueue(new Callback<SearchBean>() {
            @Override
            public void onResponse(Call<SearchBean> call, Response<SearchBean> response) {
                SearchBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        SearchBean.InfoBean info = body.getInfo();
                        history = info.getHistory();
                        hot = info.getHot();
                        if (hot != null) {
                            changeHotSearch();
                        }
                        /*显示历史搜索*/
                        if (history != null) {
                            historyAll.addAll(history);
                            adapter.addAll(historyAll);
                        }
                    } else if (code == 4200) {
                        MyToast.showToast(SearchActivity.this, "系统繁忙，请稍后重试", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<SearchBean> call, Throwable t) {
                System.out.println("SearchActivity: " + t);
                MyToast.showToast(SearchActivity.this, "系统繁忙，请稍后重试" , Toast.LENGTH_SHORT);
            }
        });
    }

    private int j;

    /*显示热门搜索*/
    private void showHotSearch() {
        if (hot != null) {
            LinearLayout ll = new LinearLayout(SearchActivity.this);
            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            ll.setLayoutParams(param);
            llHotSearch.addView(ll);
            llHotSearch.measure(0, 0);
            int width = llHotSearch.getMeasuredWidth();
            for (int i = 0; i < 8; i++) {
                final TextView textView = new TextView(SearchActivity.this);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(14, 14, 14, 14);
                textView.setLayoutParams(params);
                textView.setTextSize(14);
                textView.setText(cacheList.get(i).getTitle());
                textView.setTag(cacheList.get(i).getId());
                textView.setTextColor(getResources().getColor(R.color.tv_66));
                textView.setBackgroundResource(R.drawable.search_bg_shape);
                myLinearlayout.addView(textView);
                j = i;
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String tag = (String) textView.getTag();
                        int i1 = Integer.parseInt(tag);
                        MyToast.showToast(SearchActivity.this, "当前点击----" + i1, Toast.LENGTH_SHORT);
                    }
                });
            }
        }
    }

    /*
    * 初始化控件
    * */
    private void initView() {
        intent = new Intent();
        token = AbSharedUtil.getString(SearchActivity.this, SharedConstants.USER_TOKEN);
        searchQuit.setOnClickListener(this);
        tvBatchSearch.setOnClickListener(this);
        tvSearchClear.setOnClickListener(this);
        adapter = new SearchAdapter(SearchActivity.this);
        lvSearch.setAdapter(adapter);
    }

    /*搜索的逻辑*/
    private void Search() {
        circleEtSousuo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) SearchActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    SearchActivity.this
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    String searchContext = circleEtSousuo.getText().toString().trim();
                 //   search(searchContext);
                    intent.setClass(SearchActivity.this,SearchResultActivity.class);
                    intent.putExtra("searchkey",searchContext);
                    startActivity(intent);
                    return true;

                }
                return false;
            }
        });
    }

    /*进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断*/
    private void search(final String searchContext) {
        if (TextUtils.isEmpty(searchContext)) {
            MyToast.showToast(SearchActivity.this, "请输入内容", Toast.LENGTH_SHORT);
        } else {
            // 调用搜索的API方法
            String SousuoContent = circleEtSousuo.getText().toString().trim();
            SearchServer searchServer = ApiWrapper.getInstance().create(SearchServer.class);
            Call<SearchActivityBean> searchResult = searchServer.getSearchResult(token, searchContext);
            searchResult.enqueue(new Callback<SearchActivityBean>() {
                @Override
                public void onResponse(Call<SearchActivityBean> call, Response<SearchActivityBean> response) {
                    SearchActivityBean body = response.body();
                    if (body != null) {
                        int code = body.getCode();
                        if (code == 1) {
                            List<SearchActivityBean.UserBean> user = body.getUser();
                            List<SearchActivityBean.CircleBean> circle = body.getCircle();
                            intent.setClass(SearchActivity.this, SearchResultActivity.class);
                            Bundle mBundle = new Bundle();
                            mBundle.putSerializable("userList", (Serializable) user);
                            mBundle.putSerializable("circleList", (Serializable) circle);
                            intent.putExtras(mBundle);
                            startActivity(intent);
                        } else if (code == 0) {
                            showLoginDoalog();
                        } else if (code == 4301) {
                            intent.setClass(SearchActivity.this, SearchResultActivity.class);
                            intent.putExtra("searchkey",searchContext);
                            startActivity(intent);
                        }
                    }
                }

                @Override
                public void onFailure(Call<SearchActivityBean> call, Throwable t) {
                    MyToast.showToast(SearchActivity.this, "网络异常，请稍后重试", Toast.LENGTH_SHORT);
                }
            });


        }
    }

    /*token错误或失效*/
    AlertDialog adLogin;
    private TextView quxiaoLogin;
    private TextView quedingLogin;

    private void showLoginDoalog() {

        adLogin = new AlertDialog.Builder(SearchActivity.this).create();
        adLogin.show();
        Window window = adLogin.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiaoLogin = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        quedingLogin = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiaoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adLogin.dismiss();
            }
        });
        quedingLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.setClass(SearchActivity.this, LoginActivity.class);
                startActivity(intent);
                adLogin.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*
            * 取消
            * */
            case R.id.search_quit:
                finish();
                break;
            /*
            * 换一批
            * */
            case R.id.tv_batch_search:
                changeHotSearch();
                break;
            /*
            清空
            * */
            case R.id.tv_search_clear:
                if (historyAll != null) {
                    showQuiet();
                } else {
                    MyToast.showToast(SearchActivity.this, "暂无可清空数据", Toast.LENGTH_SHORT);
                }

                break;

        }
    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示提示用户退出的dialog*/
    private void showQuiet() {
        ad = new AlertDialog.Builder(SearchActivity.this).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.clear_search_dialog);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }

    private Set<Integer> cashSet = new HashSet<>();

    /*随机显示热门搜索*/
    private void changeHotSearch() {
        if (hot != null) {
            if (hot.size() > 8) {
                myLinearlayout.removeAllViews();
                cacheList.clear();
                cashSet.clear();
                for (int i = 0; cashSet.size() < 8; i++) {
                    cashSet.add(getRadonm(hot.size()));
                }
                List<Integer> listInteger = new ArrayList<>();
                listInteger.addAll(cashSet);
                for (int k = 0; k < listInteger.size(); k++) {
                    Integer integer = listInteger.get(k);
                    Integer integer1 = listInteger.get(k);
                    cacheList.add(hot.get(integer1));
                }
                hot.removeAll(cacheList);
                showHotSearch();
            } else {
                //热门搜索加载完毕
            }
        } else {
            MyToast.showToast(SearchActivity.this, "暂无可换一批的数据", Toast.LENGTH_SHORT);
        }
    }

    /*随机从热搜的集合中取出数据*/
    private int getRadonm(int max) {
        int num = 0;
        if (max > 1) {
            num = new Random().nextInt(max);
        }
        Log.e("1111", "num" + num);
        return num;
    }

    /*刷新历史搜索*/
    private void notifyHosity() {
        token = AbSharedUtil.getString(SearchActivity.this, SharedConstants.USER_TOKEN);
        SearchServer searchServer = ApiWrapper.getInstance().create(SearchServer.class);
        Call<SearchBean> search = searchServer.getSearch(token);
        search.enqueue(new Callback<SearchBean>() {
            @Override
            public void onResponse(Call<SearchBean> call, Response<SearchBean> response) {
                SearchBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        SearchBean.InfoBean info = body.getInfo();
                        history = info.getHistory();
                        /*显示历史搜索*/
                        if (history != null) {
                            historyAll.addAll(history);
                            adapter.addAll(historyAll);
                        }
                    } else if (code == 4200) {
                        MyToast.showToast(SearchActivity.this, "网络错误，请稍后重试！", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<SearchBean> call, Throwable t) {
                MyToast.showToast(SearchActivity.this, "网络错误，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }
}
